import axios from 'axios'
import { user } from '.'

export interface WxLoginResult {
  ok: boolean
  openid: string
}

export abstract class UserApi {
  public static async login(username: string, password: string) {
    try {
      const res = await axios.post('user/login/', {
        username,
        password,
      })
      const data = res.data
      user.login(data.user_id, data.token, data.user_name, data.name)
      return true
    }
    catch (err) {
      return false
    }
  }

  public static async wxlogin(code: string): Promise<WxLoginResult> {
    try {
      const res = await axios.post('user/wxlogin/', {
        code,
      })
      const data = res.data
      if (!data.status) {
        return {
          ok: false,
          openid: data.openid,
        }
      }
      user.login(data.user_id, data.token, data.user_name, data.name)
      return {
        ok: true,
        openid: data.openid,
      }
    }
    catch (err) {
      console.error(err)
      return {
        ok: false,
        openid: '',
      }
    }
  }
}
